package cn.qingfeng.nio.blocking.simpleio.nothread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("服务端已启动，等待客户端连接...");

            while (true) { // 持续接受客户端连接
                try (
                        Socket socket = serverSocket.accept();
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
                ) {
                    System.out.println("客户端已连接");
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println("收到客户端消息: " + inputLine);
                        // 这里可以处理接收到的消息，例如转发、存储等
                        out.println("服务端回复: " + inputLine); // 简单回复客户端相同的消息
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("服务端启动失败: " + e.getMessage());
        }
    }
}